//
//  ViewController.m
//  15-UICollectionViewLifeCycle
//
//  Created by Snow on 16/8/3.
//  Copyright © 2016年 Snow. All rights reserved.
//

#import "ViewController.h"
#import "MyCollectionViewCell.h"
#define kColor [UIColor colorWithRed:arc4random() % 256 / 255.0f green:arc4random() % 256 / 255.0f blue:arc4random() % 256 / 255.0f alpha:1]
#define kReuse @"cell"
@interface ViewController ()<UICollectionViewDelegate, UICollectionViewDataSource>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    flow.itemSize = CGSizeMake((self.view.frame.size.width - 15) / 2, 100);
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flow];
    flow.minimumLineSpacing = 5;
    flow.minimumInteritemSpacing = 5;
    flow.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    collectionView.delegate = self;
    collectionView.dataSource = self;
    [self.view addSubview:collectionView];
    [collectionView registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:kReuse];
    //关于collectionview lifeCycle
    //1.numberOfsection
    //2.collectionview:numberOfitemInsection
    //3.prepareforreuse(从重用池取出时调用)
    //4.collectionview cellforitemAtIndexPath
    //5.collectionview:willdisplaycell
    //注意:3-5循环执行
    //当cell完全离开屏幕时
    //6.collectionview:didEnddisplay
    
    //iOS 10以前
    //出屏幕立即返回,依旧进入重用池3-4-5
    //iOS10以后 出屏幕会执行4-5 不会执行3 提高了效率
}
#pragma mark - coolectionView LifeCycle
//区数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    NSLog(@"[%@:%s]",self, __FUNCTION__);
    return 1;
}
//区里的cell个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSLog(@"[%@:%s]",self, __FUNCTION__);
    return 100;
}
//从重用池取出cell
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kReuse forIndexPath:indexPath];
    cell.backgroundColor = kColor;
    return cell;
}
//iOS8.0以后推出 cell将要显示在屏幕上时
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%@----%ld----[%@:%s]", cell, indexPath.row, self, __FUNCTION__);
}
//cell已经离开屏幕时
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(nonnull UICollectionViewCell *)cell forItemAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    NSLog(@"%@----%ld----[%@:%s]", cell, indexPath.row, self, __FUNCTION__);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
